//index.js
//获取应用实例
const app = getApp()
var util = require('../../utils/util')
// var areaCats = new Array('省际物流','省内物流','空运','海运','配载调车')
var jiazhaoCats = ['请选择','无','A1','A2','A3','B1','B2','C1','C2']
var jialingCats = ['请选择','无','1-2年','3-4年','4-5年','5年以上']
var gongziCats = ['请选择','面议','1000-3000元','3000-5000元','5000-8000元','8000以上']
/*var worktypeCats = ['请选择','司机','叉车工','物流会计','客服','物流专员/助理','物流经理/主管','物流总监','调度员','快递员','仓库管理员','仓库经理/主管','装卸/搬运工','供应链管理','单证员','国际货运','分拣员','物料管理','货运代理','集装箱业务','海关事务管理','物流/仓储项目管理','集装箱维护','集装箱操作','物流销售','船务/空运陆运操作','订单处理员','水运/陆运/空运销售'];*/
var worktypeCats = ['请选择','司机','叉车工','物流会计','客服','物流专员','物流经理主管','物流总监','调度员','快递员','仓库管理员','仓库主管','装卸/搬运工','供应链管理','单证员','国际货运','分拣员','物料管理','货运代理','集装箱业务','海关事务管理','集装箱维护','集装箱操作','物流销售','订单处理员','物流/仓储项目','船务操作','空陆运操作'];
var xueliCats = ['请选择','高中','大专','本科','硕士','博士','其他']
var zhaopinCat = 1;
var qiuzhiCat = 2;
Page({
  data: {
    item:{
      sex: 1,
      prov:'',
      city:'',
      cid:0,
      jiazhao:'请选择',
      jialing:'请选择',
      gongzi:'请选择',
      xueli:'请选择',
      birthmonth:'请选择',
      worktype:'请选择',
      fuli:'',
      content:'',
      img1:'',
      img2:'',
      img3:'',
      img4:'',
      marks:'',
      status:'',
      nickname:'',
      phone:'',
      address:'',
      cat: 0,
      catname: ''
    },
    defCat: 1,
    defSex: 1,
    form_type: 'submit',
    disabled: false,
    plain: false,
    loading: false,
    defaultsize: 'default',
    defaultimg: '../../images/company/default.jpg',
    showImgs: {
      img1: '',
      img2: '',
      img3: '',
      img4: ''
    },
    jiazhaoIndex: 0,
    jialingIndex: 0,
    gongziIndex: 0,
    xueliIndex: 0,
    worktypeIndex: 0,
    jiazhaoCats: jiazhaoCats,
    jialingCats: jialingCats,
    gongziCats: gongziCats,
    xueliCats: xueliCats,
    worktypeCats: worktypeCats,
    sextypes: [
      {name: '1', value: '男', checked: true},
      {name: '2', value: '女'},
      // {name: '3', value: '不限'}
    ],
    zhaopinCat: zhaopinCat,
    qiuzhiCat: qiuzhiCat,
    region: ['安徽', '合肥', '蜀山区'],
    customItem: '请选择',
    isLoaded: false
  },
  onLoad: function (e) {
    console.log('zhaopin add (e) --' + JSON.stringify(e));
    // 已加载设置
    this.setData({
      isLoaded: true
    })
    // --
    console.log('zhaopin add')
    // console.log(e)
    var that = this

    that.setData({
        defCat: e.catid,
      })

    // 设置页面标题
    wx.setNavigationBarTitle({
      title: app.globalData.zhaopinCatsKeyVal[e.catid]
    })

    wx.showLoading({
        title: '加载中..',
        mask: true
    })

    // 判断是否已添加公司信息
    var openid = wx.getStorageSync('openid')
    if(undefined != e && undefined != e.catid && undefined == e.zhaopinid) {
      console.log('zhaopin addddd')
      // 添加专线入口
      

      // 判断是否已注册公司信息
      wx.request({
        url: app.globalData.config.service.contactUrl+'/isregcompany',
        data: {
          openid: openid
        },
        method: 'POST',
        dataType: 'json',
        header: {
          sign: 'sign123123',
          ver: 'v1',
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res){
          wx.hideLoading();
          // console.log(res);
          if(res.data.status !== 1) {
            wx.showToast({
              title: '抱歉，请先完善公司信息',
              icon: 'none',
              duration: 3000,
              success: function(e) {
                // console.log('toast')
                // console.log(e);
                // 完善公司信息
                setTimeout(
                  function() {
                    wx.redirectTo({
                      url: '../contact/company'
                    })
                },1000)
                
              }
            })
          } else {
            var itemVal = that.data.item
            // console.log(itemVal)
            itemVal.cid = res.data.data.id;
            itemVal.nickname = res.data.data.nickname;
            itemVal.phone = res.data.data.phone;
            itemVal.address = res.data.data.address;
            itemVal.catname = app.globalData.zhaopinCatsKeyVal[that.data.defCat]
            that.setData({item:itemVal})
          }
        },
        fail: function(res) {
          wx.showToast({
            title: '抱歉，数据地址请求错误.v01',
            icon: 'none',
            // icon: 'loading',
            duration: 2000
          })
          console.log('fail');
          // coonsole.log(res);
        },
        complete: function(res) {
          // console.log('complete');
          // console.log(res)
        }
      })


      // 加载当前位置
      this.getNowLocation();
      return
    } else if (undefined != e && undefined != e.zhaopinid) {
      console.log('upupdate')
      // 修改专线入口
      wx.request({
        url: app.globalData.config.service.zhaopinUrl+'/toupdate',
        data: {
          id: e.zhaopinid,
          cid: e.cid 
        },
        method: 'POST',
        dataType: 'json',
        header: {
          sign: 'sign123123',
          ver: 'v1',
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res){
          wx.hideLoading();
          // console.log(res);
          if(res.data.status !== 1 || null == res.data.data) {
            wx.showToast({
              title: '抱歉，数据获取失败，请稍后重试',
              icon: 'none',
              duration: 3000,
              success: function(e) {
                // console.log('toast')
                // console.log(e);
                // 完善公司信息
                setTimeout(
                  function() {
                    wx.navigateBack()
                },1000)
                
              }
            })
          } else {
            var itemVal = that.data.item
            // console.log(itemVal)
            itemVal.id = res.data.data.id;
            itemVal.prov = res.data.data.prov;
            itemVal.city = res.data.data.city;
            itemVal.area = res.data.data.area;
            if (res.data.data.area != '') {
              itemVal.quyu = res.data.data.area;
            } else if (res.data.data.city != '') {
              itemVal.quyu = res.data.data.city;
            } else if (res.data.data.prov != '') {
              itemVal.quyu = res.data.data.prov;
            }
            itemVal.quyu = itemVal.quyu ? itemVal.quyu : '请选择';
            // console.log('itemVal.quyu::'+itemVal.quyu)

            itemVal.cid = res.data.data.cid;
            itemVal.content = res.data.data.content;
            itemVal.img1 = res.data.data.img1;
            itemVal.img2 = res.data.data.img2;
            itemVal.img3 = res.data.data.img3;
            itemVal.img4 = res.data.data.img4;
            itemVal.marks = res.data.data.marks;
            itemVal.status = res.data.data.status;
            itemVal.nickname = res.data.data.nickname;
            itemVal.phone = res.data.data.phone;
            itemVal.address = res.data.data.address;
            itemVal.cat = res.data.data.cat;
            var _cat = res.data.data.cat // 本地数组索引小于1
            itemVal.catname = app.globalData.zhaopinCatsKeyVal[_cat]
            itemVal.jiazhao = res.data.data.jiazhao ? res.data.data.jiazhao : '请选择';
            itemVal.jialing = res.data.data.jialing ? res.data.data.jialing : '请选择';
            itemVal.gongzi = res.data.data.gongzi ? res.data.data.gongzi : '请选择';
            itemVal.xueli = res.data.data.xueli ? res.data.data.xueli : '请选择';
            itemVal.birthmonth = res.data.data.birthmonth ? res.data.data.birthmonth : '请选择';
            itemVal.xueli = res.data.data.xueli ? res.data.data.xueli : '请选择';
            itemVal.sex = res.data.data.sex;
            if (itemVal.sex.indexOf(',') != -1) {
              console.log('have ,')
              itemVal.sex = 3
            }
            itemVal.worktype = res.data.data.worktype;
            itemVal.fuli = res.data.data.fuli;
            
            // 图片展示
            var showImgs = that.data.showImgs
            showImgs['img1'] = res.data.data.domainimg1
            showImgs['img2'] = res.data.data.domainimg2
            showImgs['img3'] = res.data.data.domainimg3
            showImgs['img4'] = res.data.data.domainimg4

            that.setData({
              item:itemVal,
              showImgs: showImgs
            })
          }
        },
        fail: function(res) {
          wx.showToast({
            title: '抱歉，数据地址请求错误.v03',
            icon: 'none',
            duration: 2000
          })
          console.log('fail');
        },
        complete: function(res) {
          // console.log('complete');
          // console.log(res)
        }
      })
    } else {
      util.showError('抱歉，数据异常')
      return
    }
    
  },
  onShow: function(e) {
    var that = this
    // 每次打开小程序时候，获取当前位置
    console.log('onshow');

    // 控制非后台打开不刷新
    /*var showIden5 = wx.getStorageSync('showIden5');
    var showIden5Global = app.globalData.showIden5;
    if (showIden5 == showIden5Global) {
      return;
    } else {
      wx.setStorage({
        key: 'showIden5',
        data: showIden5Global
      });
    }*/

    /*if (this.data.isLoaded) {
      this.getNowLocation(); // 放在 onShow 的目的是当小程序启动，或从后台进入前台显示都获取当前位置并实时查询
    }*/
    console.log('onshow end')
  },
  formSubmit:function(e){
    wx.showLoading({
      title: '正在提交...',
      mask:true
    })

    var that=this
    // 提交校验
    /*else if (formdata.jiazhao=='请选择') {
      util.showMaskTip1500('请选择驾照类型')
    }*/ 

    var formdata = e.detail.value
    if (formdata.quyu=='') {
      util.showMaskTip1500('请选择发布城市或地区')
    }
    else if(formdata.birthmonth=='请选择') {
      util.showMaskTip1500('请选择出生年月')
    }
    else if(formdata.xueli=='请选择') {
      util.showMaskTip1500('请选择学历')
    }
    else if(formdata.jialing=='请选择') {
      util.showMaskTip1500('请选择工作经验')
    }
    else if(formdata.worktype=='请选择') {
      util.showMaskTip1500('请选择岗位')
    } 
    else if(formdata.gongzi=='请选择') {
      util.showMaskTip1500('请选择工资')
    } else if (formdata.nickname == '') {
      util.showMaskTip1500('联系人不能为空')
    } else if (formdata.phone == '') {
      util.showMaskTip1500('手机号码不能为空')
    } else if (formdata.address == '') {
      util.showMaskTip1500('地址不能为空')
    } else if (formdata.cid == '') {
      util.showMaskTip1500('抱歉，联系人信息异常，请重新加载后重试')
    } else {
      //提交
      var reqUrl = app.globalData.config.service.zhaopinUrl+'/add';
      wx.request({
        url: reqUrl,
        method: 'POST',
        dataType: 'json',
        header: {
          sign: 'sign123123',
          ver: 'v1',
          "content-type": "application/x-www-form-urlencoded"
        },
        data: formdata,
        success: function(res){
          wx.hideLoading();
          if(res.data.status !== 1) {
            util.showError('发布失败')
          } else {
            wx.showToast({
              title: '发布成功',
              icon: 'success',
              duration: 2000,
              mask: true,
              success: function(res) {
                setTimeout(
                  function() {
                    wx.redirectTo({url: '../contact/zhaopins'})
                },1000)
              }
            })
          }
        },
        fail: function(res) {
          util.showError('抱歉，数据地址请求错误.v02')
          console.log('fail');
          // coonsole.log(res);
        },
        complete: function(res) {
          console.log('complete');
          // console.log(res)
        }
      })
    }
  },/*
  radioChange (e) {
    this.setData({
      'item.sex': e.detail.value
    })
  },*/
  bindWorktypeChange (e) {
    this.setData({
      worktypeIndex: e.detail.value,
      "item.worktype": worktypeCats[e.detail.value]
    })
  },
  bindJiazhaoChange (e) {
    this.setData({
      jiazhaoIndex: e.detail.value,
      "item.jiazhao": jiazhaoCats[e.detail.value]
    })
  },
  bindXueliCatsChange (e) {
    this.setData({
      xueliIndex: e.detail.value,
      "item.xueli": xueliCats[e.detail.value]
    })
  },
  bindJialingChange (e) {
    this.setData({
      jialingIndex: e.detail.value,
      "item.jialing": jialingCats[e.detail.value]
    })
  },
  bindGoongziChange (e) {
    this.setData({
      gongziIndex: e.detail.value,
      "item.gongzi": gongziCats[e.detail.value]
    })
  },
  bindXueliChange (e) {
    this.setData({
      xueliIndex: e.detail.value,
      "item.xueli": xueliCats[e.detail.value]
    })
  },
  bindDateChange (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      'item.birthmonth': e.detail.value
    })
  },
  bindFuliBlur (e) {
    this.setData({
      "item.fuli": e.detail.value
    })
  },
  bindWordChg (e) {
    this.setData({
      "item.content": e.detail.value
    })
  },
  /*bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value,
      "item.quyu": e.detail.value
    })
  },*/

  toSelectQuyu (e) {
    // 求职区域
    var areaCat = app.globalData.zxCatShinei;
    var nowAreaVal = this.data.item.city
    var nowAreaCatStr = 'city'
    // 选择
    wx.navigateTo({
      url:"../city2/index?direction=item.quyu&cat="+areaCat+"&nowAreaVal="+nowAreaVal+"&nowAreaCatStr="+nowAreaCatStr
    })
  },
  changeCity (e) {
    console.log('changeCity')
    // 选中的城市值赋值
    console.log(e)
    var setCityDirection = e.direction
    if (setCityDirection == 'item.quyu') {
      var cityVal = util.getZhuanxianShow(e);
      this.setData({
        'item.prov': e.selectedProv,
        'item.city': e.selectedCity,
        'item.area': e.selectedArea,
        'item.quyu': cityVal
      })
    }
  },
  checkImg:function(e){
    var imgId = e.currentTarget.id
    //点击选择图片
    var that=this
    console.log(that);
    
    wx.chooseImage({
    count: 1,
    success: function (res) {
      var tempFilePaths = res.tempFilePaths

      console.log(res)

      // 上传到服务器
      wx.uploadFile({
        url: app.globalData.config.service.uploadUrl, //仅为示例，非真实的接口地址
        filePath: tempFilePaths[0],
        name: 'file',
        header: {
          'content-type': 'multipart/form-data'
        },
        formData:{
          'from': 'zhaopin'
        },
        success: function(res){
          console.log('upload res::')
          // console.log(res)
          var data = res.data
          // console.log(res);
          var jsonData = JSON.parse(data)
          // console.log(jsonData);
          // console.log(jsonData.status);

          if (jsonData.status != 1) {
            util.showError(jsonData.message)
          } else {
            var showImgs = that.data.showImgs;
            var item = that.data.item;

            var imgUploadUrl = jsonData.data.imgurl
            item[imgId] = imgUploadUrl;

            // 设置本地展示
            showImgs[imgId] = tempFilePaths[0];
            that.setData({
              item:item,
              showImgs:showImgs
            })
            console.log(that.data)
          }
        },
        fail: function() {
          util.showError('上传失败')
        }
      })
    }
    })
  },
  getNowLocation: function(e) {
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        var latitude = res.latitude
        var longitude = res.longitude
        // 调用百度API获取位置具体地址名
        wx.request({
          url: app.globalData.config.service.baiduApi+'&location=' + latitude + ',' + longitude + '&output=json&coordtype=wgs84ll', 
          data: { },
          header: { 'Content-Type': 'application/json' },
          success: function(res) {
            // console.log(res)
            // console.log(typeof(res.data.status));
            // console.log(res.data.result.addressComponent.city);
            if(res.data.status==0) {
              var locationInfo = res.data.result.addressComponent
              // console.log(locationInfo)
              var provStr = locationInfo.province
              if (provStr.indexOf('市')!=-1 && provStr.length>2){
                provStr = provStr.replace(/(.*)市/, '$1')
              }
              var cityStr = locationInfo.city

              if (cityStr.indexOf('市')!=-1 && cityStr.length>2){
                cityStr = cityStr.replace(/(.*)市/, '$1')
              }
              var cityStrShow = cityStr
              if (provStr == cityStr) {
                cityStr = '辖区';
              }
              that.setData({
                "item.prov":provStr,
                "item.city":cityStr,
                "item.quyu":cityStrShow
              })
            }
          }
        })
      }
    })
  }
})
